#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int largestRectangleArea(int *heights, int heightsSize) {
    int ans[heightsSize + 2];
    ans[0] = 0;
    ans[heightsSize + 1] = 0;
    for (int i = 0; i < heightsSize; ++i) {
        ans[i + 1] = heights[i];
    }
    int stack[heightsSize + 2];
    int top = -1;
    stack[++top] = 0;
    int max = 0;
    for (int i = 1; i < heightsSize + 2; ++i) {
        while (ans[i] < ans[stack[top]]) {
            printf(" %d  %d  ans[stack[top]]  %d \n", i, stack[top - 1], ans[stack[top]]);

            max = fmax(max, (i - stack[top - 1] - 1) * ans[stack[top]]);
            --top;
        }
        stack[++top] = i;
    }
    return max;
}

int main() {
    setbuf(stdout, 0);
    int test[] = {2, 1, 5, 6, 2, 3};
    int ret = largestRectangleArea(test, 6);
    printf(" %d\n", ret);
}